/*
 * Copyright (C) 2009 Internal Innovation Technology(IIT)
 * 
 */
package com.iitbd.hxcalc;

import com.jgoodies.looks.plastic.Plastic3DLookAndFeel;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.util.Date;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JFrame;
import javax.swing.JProgressBar;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

/**
 *
 * @author Prasun Kanti Howlader <prasun@iitbd.com>
 */
public class HxCalc {

    private static Logger logger = Logger.getLogger(HxCalc.class.getName());
    static AppConfig config;
    private static Splash splash = null;
    private Timer theTimer;
    static HxCalc instance = new HxCalc();
    static JProgressBar progressBar;
    public Utilities utils = null;

    public HxCalc() {
        utils = new Utilities();
    }

    public static AppConfig getConfig() {
        return config;
    }

    public Utilities getUtils() {
        return utils;
    }

    public void runProgressBar(int seconds) {
        //We are gonna update the progress bar 10 times a second

        splash.progressBar.setMaximum(5 * 10);

        theTimer = new Timer();

        //100ms means we update 10 times a second
        theTimer.schedule(new ProgressBarTimerTask(), new Date(), 100);

    }

    private class ProgressBarTimerTask extends TimerTask {

        public void run() {
            int currentProgressBarValue = progressBar.getValue();

            //If we have filled the progress bar up then we can cancel
            //the timer.
            if (currentProgressBarValue == progressBar.getMaximum()) {
                theTimer.cancel();
                theTimer = null;
                splash.dispose();
                HCalcMain();


            } //If we haven't filled the progress bar up yet, add another
            //one on
            else {
                progressBar.setValue(currentProgressBarValue + 1);
            }
        }
    }

    public static void main(final String args[]) {
        System.setProperty("jna.library.path", System.getProperty("user.dir") + File.separatorChar + "lib");
        checkLogFiles(AppDefaults.appdir);
        checkConfigFiles(AppDefaults.appdir);
        initializeGUI();
        splash = new Splash();
        progressBar = splash.getProgressBar();
        splash.setLocationRelativeTo(null);
        /*
         * splash.addKeyListener(new KeyAdapter() {
         *
         * @Override public void keyPressed(KeyEvent k) {
         *
         * if (k.getKeyCode() == KeyEvent.VK_ESCAPE) {
         * instance.theTimer.cancel(); splash.dispose(); HCalcMain();
         *
         * }
         *
         * }
         * });
         */
        splash.addMouseListener(new MouseAdapter() {

            @Override
            public void mouseClicked(MouseEvent me) {
                instance.theTimer.cancel();
                splash.dispose();
                HCalcMain();
            }
        });

        splash.setVisible(true);
        instance.runProgressBar(5);



    }

    private static void loadFrame() throws Exception {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                try {
                    HxcalcUI mainWindow = new HxcalcUI();
                    mainWindow.setIconImage(java.awt.Toolkit.getDefaultToolkit().getImage(HxCalc.class.getClassLoader().getResource("resources/images/logo.jpg")));
                    mainWindow.setTitle(Resources.getString("appTitle"));
                    //mainWindow.setDefaultLookAndFeelDecorated(true);
                    mainWindow.pack();
                    //mainWindow.setExtendedState(mainWindow.getExtendedState() | JFrame.MAXIMIZED_BOTH);
                    mainWindow.setSize(1265, 740);
                    Toolkit kit = mainWindow.getToolkit();
                    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
                    GraphicsDevice[] gs = ge.getScreenDevices();
                    Insets in = kit.getScreenInsets(gs[0].getDefaultConfiguration());

                    Dimension d = kit.getScreenSize();
                    int max_width = (d.width - in.left - in.right);
                    int max_height = (d.height - in.top - in.bottom);
                    //frm.setSize(Math.min(max_width, 850), Math.min(max_height, 550));//whatever size you want but smaller the insets
                    mainWindow.setLocation((int) (max_width - mainWindow.getWidth()) / 2, (int) (max_height - mainWindow.getHeight()) / 2);

                    mainWindow.setResizable(false);

                    mainWindow.setVisible(true);
                    mainWindow.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                } catch (Exception e) {
                    throw new IllegalArgumentException(e);
                }
            }
        });
    }

    /**
     * Check if log file exists.The log file resides into the log folder.
     *
     * @param fileLocation takes the log file name
     * @return true if hcalc.log exists or false
     */
    private static boolean checkLogFiles(String fileLocation) {
        try {
            File f = new File(fileLocation + AppDefaults.PATH_SEPARATOR + "logs");
            if (!f.exists()) {
                if (!f.mkdirs()) {
                    return false;
                }
            }

            String logFileName = f.getAbsolutePath() + AppDefaults.PATH_SEPARATOR
                    + "hcalc.log";
            System.setProperty("logfile.name", logFileName);

            PropertyConfigurator.configure(HxCalc.class.getClassLoader().getResource("resources/log4j.properties"));
            logger.info("Loading log file");
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * Check if config file exists.The config file resides into the conf folder.
     *
     * @param fileLocation takes the conf file name
     * @return true if conf file exists or false
     */
    private static boolean checkConfigFiles(String fileLocation) {
        try {
            File f = new File(fileLocation + AppDefaults.PATH_SEPARATOR + "conf");
            if (!f.exists()) {
                if (!f.mkdirs()) {
                    return false;
                }
            }
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * Set the jgoodies plastic look and feel
     */
    private static void initializeGUI() {
        try {

            UIManager.setLookAndFeel(new Plastic3DLookAndFeel());
            
            UIManager.put("ProgressBar.foreground", new Color(0x205092));  //colour of progress bar
            logger.info("Current laf: " + UIManager.getLookAndFeel().getName());
        } catch (UnsupportedLookAndFeelException el) {
            logger.info("Failed to load look and feel");
        }

    }

    public static void HCalcMain() {
        try {

            System.out.print("Hello") ;
            config = new AppConfig();
            config.load();

            // set Locale.

            String slang = config.getProperty("user.language");

            String scountry = config.getProperty("user.country");


            if (slang != null && !slang.equals("") && scountry != null) {
                Locale.setDefault(new Locale(slang, scountry));
            }

            Resources.resourceInitialize();


            loadFrame();
        } catch (Exception e) {
        }
    }
}
